package com.party.admin.web.controller.enterpriseservice;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.party.core.utils.MyBeanUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.city.City;
import com.party.core.model.enterpriseservice.EpCategory;
import com.party.core.model.enterpriseservice.EpCategoryCity;
import com.party.core.model.enterpriseservice.EpService;
import com.party.core.model.enterpriseservice.EpServiceCategory;
import com.party.core.model.mall.MallCategory;
import com.party.core.service.enterpriseservice.IEpCategoryCityService;
import com.party.core.service.enterpriseservice.IEpCategoryService;
import com.party.core.service.enterpriseservice.IEpServiceCategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @program: party
 * @description: 企业服务类型控制器
 * @author: Hua Qunhao
 * @create: 2019-01-08 16:45
 */
@Controller
@RequestMapping(value = "/epService/category")
public class EnterpriseCategoryController {
    @Autowired
    private IEpCategoryService epcategoryService;

    @Autowired
    private IEpCategoryCityService epCategoryCityService;

    @Autowired
    private IEpServiceCategoryService epServiceCategoryService;

    Logger logger = LoggerFactory.getLogger(EnterpriseCategoryController.class);


    /**
     * 服务分类列表
     *
     * @param epCategory 类型
     * @param page       分页参数
     * @return 交互数据
     */
    @RequestMapping(value = "list")
    public ModelAndView listNew(EpCategory epCategory, Page page) {
        page.setLimit(10);
        ModelAndView modelAndView = new ModelAndView("enterpriseservice/epCategoryList");
        List<EpCategory> list = epcategoryService.listPage(epCategory, page);
        modelAndView.addObject("list", list);
        modelAndView.addObject("page", page);
        return modelAndView;
    }


    /**
     * 服务类型视图
     *
     * @param epCategory 分类信息
     * @return 交互数据
     */
    @RequestMapping(value = "categoryView")
    public ModelAndView categoryForm(EpCategory epCategory) {
        ModelAndView modelAndView = new ModelAndView("enterpriseservice/epCategoryView");
        if (StringUtils.isNotEmpty(epCategory.getId())) {
            epCategory = epcategoryService.get(epCategory.getId());

            List<City> categoryList = epCategoryCityService.queryCityListByCategoryId(epCategory.getId());

            modelAndView.addObject("epCategory", epCategory);
            modelAndView.addObject("categoryList", categoryList);
        }
        return modelAndView;
    }


    /**
     * 验证分类唯一性
     *
     * @param name 分类名称
     * @return
     */
    @ResponseBody
    @RequestMapping("verifyName")
    public AjaxResult verifyName(String name, String id) {
        if (StringUtils.isEmpty(name)) {
            return AjaxResult.error("分类名称不能为空");
        }
        EpCategory epCategory = epcategoryService.findEpCategoryByName(name);
        if (epCategory != null && !(epCategory.getId().equals(id))) {
            return AjaxResult.error("分类名称已存在");
        }
        return AjaxResult.success();
    }


    /**
     * 删除分类
     *
     * @param id 分类id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        EpServiceCategory epServiceCategory = new EpServiceCategory();
        epServiceCategory.setCategoryId(id);
        List<EpServiceCategory> list = epServiceCategoryService.list(epServiceCategory);
        if (list.size() > 0) {
            return AjaxResult.error("分类下存在服务,不能直接删除");
        }
        epcategoryService.delete(id);
        epCategoryCityService.deleteEpCategoryCityByCid(new EpCategoryCity(null, id));
        return AjaxResult.success();
    }


    /**
     * 服务分类保存
     *
     * @param epCategory 服务分类
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxResult save(EpCategory epCategory, BindingResult result) {
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }

        try {

            if (StringUtils.isNotEmpty(epCategory.getId())) {
                EpCategory t = epcategoryService.get(epCategory.getId());

                MyBeanUtils.copyBeanNotNull2Bean(epCategory, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
                epcategoryService.update(t);

                if (StringUtils.isNotEmpty(epCategory.getCategoryList()) && epCategory.getCategoryList().length() > 0) {

                    String categoryids = epCategory.getCategoryList();
                    //添加没有的类型
                    for (String categoryId : categoryids.split(",")) {
                        EpCategoryCity epCategoryCity = epCategoryCityService.findByCategoryCitybyCid(new EpCategoryCity(categoryId, epCategory.getId()));

                        if (epCategoryCity == null) {
                            epCategoryCity = new EpCategoryCity(categoryId, epCategory.getId());
                            epCategoryCityService.insert(epCategoryCity);
                        }
                    }
                    //删除没有的类型
                    List<EpCategoryCity> epCategoryCityList = epCategoryCityService.list(new EpCategoryCity(null, epCategory.getId()));

                    List<String> oldcityLists = LangUtils.transform(epCategoryCityList, input -> input.getCityId());
                    List<String> cityIds = Arrays.asList(categoryids.split(","));
                    oldcityLists.removeAll(cityIds);


                    for (String oldId : oldcityLists) {
                        epCategoryCityService.deleteEpCategoryCityByCid(new EpCategoryCity(oldId, epCategory.getId()));
                    }
                }

            } else {

                epcategoryService.insert(epCategory);
                if (StringUtils.isNotEmpty(epCategory.getCategoryList()) && epCategory.getCategoryList().length() > 0) {
                    for (String cityId : epCategory.getCategoryList().split(",")) {

                        epCategoryCityService.insert(new EpCategoryCity(cityId, epCategory.getId()));
                    }
                }
            }

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存分类异常", e);
            return AjaxResult.error("保存分类异常");
        }
    }


    /**
     * 获取分类列表
     *
     * @return 分类列表
     */
    @RequestMapping("/selectEpCategoryList")
    public ModelAndView categoryList(EpCategory category, Page page, String categoryIds) {
        page.setLimit(10);
        ModelAndView modelAndView = new ModelAndView("enterpriseservice/selectEpCategoryList");

        List<EpCategory> epCategoryList = epcategoryService.listPage(category, page);

        modelAndView.addObject("list", epCategoryList);
        modelAndView.addObject("page", page);
        modelAndView.addObject("categoryIds", categoryIds);


        Set<String> allCategoryIds = Sets.newHashSet();
        if (com.party.common.utils.StringUtils.isNotEmpty(categoryIds)) {
            allCategoryIds.addAll(Arrays.asList(categoryIds.split(",")));
        }
        if (allCategoryIds.size() > 0) {
            List<EpCategory> mallCategories = epcategoryService.batchList(allCategoryIds, new EpCategory(), null);
            mallCategories = LangUtils.transform(mallCategories, input -> {
                EpCategory epCategory = new EpCategory();
                epCategory.setId(input.getId());
                epCategory.setName(input.getName());
                return epCategory;
            });
            modelAndView.addObject("categoryJson", JSONObject.toJSONString(mallCategories));
        } else {
            modelAndView.addObject("categoryJson", JSONObject.toJSONString(new ArrayList<EpCategory>()));
        }
        return modelAndView;
    }
}
